package com.zhong.auth.domain.service.impl;

import com.alibaba.fastjson.JSON;
import com.zhong.auth.common.enums.IsDeleteFlagEnum;
import com.zhong.auth.domain.bo.AuthRolePermissionBO;
import com.zhong.auth.domain.convert.AuthRolePermissionBOConvert;
import com.zhong.auth.domain.service.AuthRolePermissionDomainService;
import com.zhong.auth.infra.basic.entity.AuthRolePermission;
import com.zhong.auth.infra.basic.service.AuthRolePermissionService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class AuthRolePermissionDomainServiceImpl implements AuthRolePermissionDomainService {

    @Resource
    private AuthRolePermissionService authRolePermissionService;

    @Override
    public Boolean add(AuthRolePermissionBO authRolePermissionBO) {
        if (log.isInfoEnabled()){
            log.info("AuthRolePermissionDomainServiceImpl.add.AuthRolePermissionBO: {}", JSON.toJSONString(authRolePermissionBO));
        }
        Long roleId = authRolePermissionBO.getRoleId();
        List<AuthRolePermission> authRolePermissionList = new ArrayList<>();
        authRolePermissionBO.getPermissionIdList().forEach(permissionId->{
            AuthRolePermission authRolePermission = AuthRolePermission.builder()
                    .isDelete(IsDeleteFlagEnum.UN_DELETE.getCode())
                    .roleId(roleId)
                    .permissionId(permissionId)
                    .build();
            authRolePermissionList.add(authRolePermission);
        });
        int count = authRolePermissionService.insertBatch(authRolePermissionList);

        return count > 0;
    }

    @Override
    public Boolean delete(AuthRolePermissionBO authRolePermissionBO) {
        if (log.isInfoEnabled()){
            log.info("AuthRolePermissionDomainServiceImpl.delete.AuthRolePermissionBO: {}", JSON.toJSONString(authRolePermissionBO));
        }
        AuthRolePermission authRolePermission = AuthRolePermissionBOConvert.INSTANCE.convertBOToEntity(authRolePermissionBO);
        authRolePermission.setIsDelete(IsDeleteFlagEnum.DELETE.getCode());
        Integer count = authRolePermissionService.update(authRolePermission);
        return count > 0;
    }

    @Override
    public Boolean update(AuthRolePermissionBO authRolePermissionBO) {
        if (log.isInfoEnabled()){
            log.info("AuthRolePermissionDomainServiceImpl.update.AuthRolePermissionBO: {}", JSON.toJSONString(authRolePermissionBO));
        }
        AuthRolePermission authRolePermission = AuthRolePermissionBOConvert.INSTANCE.convertBOToEntity(authRolePermissionBO);
        Integer count = authRolePermissionService.update(authRolePermission);
        return count > 0;
    }
}
